<?php

class DefaultController extends Controller
{

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array(''),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('chapnhanthanhtoan','thanhtoan','viewthanhtoan','excel','nhaphoadon','index','view','create','update','admin','chinhsuathanhcong','delete','thanhcong','load'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array(''),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	public function actionChapNhanThanhToan()
	{
		header('Access-Control-Allow-Origin: *');
		header('Content-type: application/json');
		$status = array(
			'status'=>false,
			'info'=>'Lỗi',
		);
		if (isset($_POST["idhoadon"]) && isset($_POST["so_chung_tu"]) && isset($_POST["id"]) && isset($_POST["date"])) {
			$idarrs  = $_POST["idhoadon"];
			$so_chung_tu = $_POST["so_chung_tu"];
			$id = $_POST["id"];
			$date = $_POST["date"];
			$model = Doitac::model()->findByPk($id);
			if ($model == null) {
				echo json_encode($status);
				exit;
			}
			$count = count($idarrs);
			$tongtien = Doitac::getSotienthanhtoan($idarrs);
			if ($count  > 1) {
				$dt_thanhtoan = new DoitacThanhtoan;
				$dt_thanhtoan->id_doitac = $model->id;
				$dt_thanhtoan->tien_thanhtoan = $tongtien;
				$dt_thanhtoan->so_chungtu = $so_chung_tu;
				$dt_thanhtoan->ngay_tao = date("Y-m-d H:i:s",strtotime($date));
				if ($dt_thanhtoan->save(false)) {
					foreach ($idarrs as $key) {
						$value = DoitacKhachhang::model()->findByPk($key);
						if ($value != null) {
							$value->chua_thanh_toan_dt = 0;
							$value->trangthai_thanhtoan_dt = 2;
							$value->ngay_thanh_toan_dt = $dt_thanhtoan->ngay_tao;
							$value->chung_tu_thanh_toan = $so_chung_tu;
							$value->save(false);
						}
					}
					$model->da_thanh_toan += $tongtien;
					$model->chua_thanh_toan = Doitac::GetSoTienChuaThanhToan($model);
					$model->save(false);
					$status['status'] = true;
					$status['info'] = "Đã thanh toán thành công {$count} hóa đơn";
				}
			}else{
				$so_tien = 0;
				if (isset($_POST['so_tien'])) {
					$so_tien = $_POST['so_tien'];
				}
				$dt_thanhtoan = new DoitacThanhtoan;
				$dt_thanhtoan->id_doitac = $model->id;
				$dt_thanhtoan->tien_thanhtoan = $so_tien;
				$dt_thanhtoan->so_chungtu = $so_chung_tu;
				$dt_thanhtoan->ngay_tao = date("Y-m-d H:i:s",strtotime($date));
				if ($dt_thanhtoan->save(false)) {
					$hoadon = DoitacKhachhang::model()->findByPk($idarrs[0]);
					if ($hoadon != null) {
						if ($so_tien == $hoadon->chua_thanh_toan_dt) {
							$hoadon->trangthai_thanhtoan_dt = 2;
							$hoadon->chung_tu_thanh_toan = $so_chung_tu;
							$hoadon->ngay_thanh_toan_dt = $dt_thanhtoan->ngay_tao;
							$status['info'] = "Đã thanh toán thành công hóa đơn";
						}else{
							$hoadon->trangthai_thanhtoan_dt = 1;
							$status['info'] = "Đã thanh toán một phần hóa đơn";
						}
						$hoadon->chua_thanh_toan_dt -= $so_tien; 
						$hoadon->save(false);
						$model->da_thanh_toan += $so_tien;
						$model->chua_thanh_toan -= $so_tien;
						$model->chua_thanh_toan = Doitac::GetSoTienChuaThanhToan($model);
						$model->save(false);
					}
					$status['status'] = true;
					
				}
			}
			echo json_encode($status);
		}
	}
	public function actionThanhToan($id)
	{
		$model = $this->loadModel($id);
		$data = DoitacKhachhang::model()->search("id_doitac = $id");
		$this->render('thanhtoan',array(
			'model'=>$model,
			'data'=>$data,
		));
	}
	public function actionViewThanhToan()
	{
		if (isset($_POST['id']) && isset($_POST['data'])) {
			$id = $_POST['id'];
			$arrs = json_decode($_POST['data']);
			$count = count($arrs);
			$model = Doitac::model()->findByPk($id);
			if ($model != null && $count > 0) {
				$tongtien = 0;
				$tongtien = Doitac::getSotienthanhtoan($arrs);
				$this->renderPartial('viewthanhtoan',array(
										'model'=>$model,
										'count'=>$count,
										'tongtien'=>$tongtien,
										'arrs'=>$arrs
										));
			}
		}
	}
	public function actionLoad()
	{
		if (isset($_POST['p'])) {
			$p = $_POST['p'];
			$model = Doitac::model()->findAll("ten like '%$p%' or ma_so like '%$p%' ");
			$arrs = array();$i=0;
			foreach ($model as $key => $value) {
				$arr =array(
					'name'=>$value->ten,
					'id' =>$value->id,
				);
				$arrs[$i++] = $arr;
			}
			echo json_encode($arrs);
		}
	}
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	public function actionExcel($id)
	{
		$model = $this->loadModel($id);
		Doitac::createExcel($model);	
	}
	public function actionChinhSuaThanhCong()
	{
		$this->render('chinhsuathanhcong');
	}
	public function actionThanhCong()
	{
		$this->render('thanhcong');
	}
	public function actionNhapHoaDon()
	{
		$criteria=new CDbCriteria;
		$criteria->order = "id desc";
		if (isset($_GET['id'])) {
			$id =  $_GET['id'];
			$criteria->condition = "id_doitac = $id";
		}
		$data = new CActiveDataProvider('DoitacKhachhang', array(
			'criteria'=>$criteria,
		));
		$this->render('nhaphoadon',array('data'=>$data));
	}
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Doitac;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Doitac']))
		{
			$model->attributes=$_POST['Doitac'];
			$model->ngay_vao_so = date("Y-m-d H:i:s");
			$text_loaihinh = $_POST["text_loaihinh"];
			$loaihinhkd = Loaihinhkinhdoanh::model()->findByPk($model->id_loai_hinh_kinhdoanh);
			if ($loaihinhkd == null) {
				$loaihinhkd = Loaihinhkinhdoanh::model()->findByAttributes(array('ten_loaihinh'=>$text_loaihinh));
				if ($loaihinhkd == null) {
					$loaihinhkd = new Loaihinhkinhdoanh;
					$loaihinhkd->ten_loaihinh = $text_loaihinh;
					$loaihinhkd->save(false);
				}
			}
			$model->id_loai_hinh_kinhdoanh = $loaihinhkd->id;
			if($model->validate()){
				// $model->cam_ket = $model->cam_ket / 100;
				$model->save();
				$this->redirect(array('thanhcong'));
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		// $model->cam_ket = $model->cam_ket * 100;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Doitac']))
		{
			$model->attributes=$_POST['Doitac'];
			$model->ngay_vao_so = date("yyyy-MM-dd H:i:s");
			$text_loaihinh = $_POST["text_loaihinh"];
			$loaihinhkd = Loaihinhkinhdoanh::model()->findByPk($model->id_loai_hinh_kinhdoanh);
			if ($loaihinhkd == null) {
				$loaihinhkd = Loaihinhkinhdoanh::model()->findByAttributes(array('ten_loaihinh'=>$text_loaihinh));
				if ($loaihinhkd == null) {
					$loaihinhkd = new Loaihinhkinhdoanh;
					$loaihinhkd->ten_loaihinh = $text_loaihinh;
					$loaihinhkd->save(false);
				}
			}
			$model->id_loai_hinh_kinhdoanh = $loaihinhkd->id;
			if($model->validate()){
				// $model->cam_ket = $model->cam_ket / 100;
				$model->save();
				$this->redirect(array('chinhsuathanhcong'));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();
		echo $id;

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Doitac');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Doitac('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Doitac']))
			$model->attributes=$_GET['Doitac'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Doitac the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Doitac::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Doitac $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='doitac-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
